package com.wuxianedu.image_loader;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

/**
 * Created by TED on 2016/10/2.
 */
public class MainActivity2 extends AppCompatActivity {

    private GridView grid;
    private ImageLoader imageLoader;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2_main);
        initViews();
    }

    private void initViews() {

        imageLoader = ImageLoader.getInstance();
        grid = (GridView) findViewById(R.id.grid_view);
        grid.setAdapter(new MyAdapter());
        // 滑动时，不加载图片， 第二个参数值，滑动时是否停止加载图片，第三个参数，猛地滑动时，是否加载图片
        grid.setOnScrollListener(new PauseOnScrollListener(imageLoader,true, true));
    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return Contents.URLS.length;
        }

        @Override
        public Object getItem(int position) {
            return Contents.URLS[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null){
                convertView = View.inflate(MainActivity2.this,R.layout.item_grid,null);
            }

            final ImageView  iv = (ImageView) convertView.findViewById(R.id.item_grid_iv);
//            imageLoader.displayImage(Contents.URLS[position],iv);
            // 给个默认的图片
            imageLoader.loadImage(Contents.URLS[position], new SimpleImageLoadingListener(){
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    iv.setImageResource(R.mipmap.ic_launcher);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    iv.setImageBitmap(loadedImage);
                }
            });
            return convertView;
        }
    }
}
